const { ObjectId } = require("mongodb");

const commentCollection = 'comment';
const secondCommentCollection = 'secondComment';
const userProfileCollection = 'userProfile';
const blogCollection = 'blog';

const deleteComment = (deleteOne) => async (req, res) => {
    const { _id, level } = req.payload;
    const collection = level == 2 ? secondCommentCollection : commentCollection;
    const del = await deleteOne(collection, _id);
    if (del) {
        return res.json({ code: 0, message: '删除成功' });
    }
    res.json({ code: 1, message: '删除失败' });
}

/**
 * @param {*} violation 决定是否违规
 */
const violationComment = (updateOne) => async (req, res) => {
    const { _id, level, violation } = req.payload;
    const collection = level == 2 ? secondCommentCollection : commentCollection;
    const item = await updateOne({ collection, _id, data: { violation } });
    if (item) {
        return res.json({ code: 0, message: '操作成功' });
    }
    res.json({ code: 1, message: '操作失败' });
}

/**
 获取评论： 区分 一级评论，二级评论，指定用户的评论 等
 */
const queryComment = (aggregate, getCollectionCounts) => async (req, res) => {
    const { level = 1, limit = 20, skip = 0, sort = { _id: -1 } } = req.payload;
    const pipeline = [
        {
            $lookup: {
                from: userProfileCollection,
                localField: 'senderId',
                foreignField: '_id',
                as: 'sender'
            }
        },
        {
            $project: {
                'sender.password': 0,
                'sender.lastUpdate': 0,
                'sender.thumbsUp': 0,
                'sender.thumbsDown': 0,
                'sender.mail': 0
            }
        },
        { $sort: sort },
        { $skip: skip },
        { $limit: limit }
    ];
    const collection = level == 2 ? secondCommentCollection : commentCollection;
    const list = await aggregate({ collection, pipeline });
    const count = await getCollectionCounts({ collection })
    res.json({ list, count }).end();
}

/**
 * @description: 评论点赞 根据 type 决定赞还是踩
 */
const thumbsComment = (updateOne) => async (req, res) => {
    const { userId, commentId, type, second } = req.payload;
    const field = type === 'UP' ? 'thumbsUp' : 'thumbsDown';
    const result = await updateOne({
        collection: second ? secondCommentCollection : commentCollection,
        _id: commentId,
        cusData: { $addToSet: { [field]: ObjectId(userId) } }
    });
    console.log("评论点赞:", result);
    res.json(result.acknowledged ? { message: '操作成功', code: 0 } : { message: '操作失败', code: -1 });
}
/**
 *取消评论点赞 根据 type 决定赞还是踩
 */
const cancelThumbsComment = (updateOne) => async (req, res) => {
    const { userId, commentId, type, second } = req.payload;
    const field = type === 'UP' ? 'thumbsUp' : 'thumbsDown';
    const result = await updateOne({
        collection: second ? secondCommentCollection : commentCollection,
        _id: commentId,
        cusData: { $pull: { [field]: ObjectId(userId) }, }
    });
    console.log("取消评论点赞:", result);
    res.json(result.acknowledged ? { message: '操作成功', code: 0 } : { message: '操作失败', code: -1 });
}

/**
    评论的点赞/踩转换
 */

const transformThumbsComment = (updateOne) => async (req, res) => {
    let { userId, commentId, from, to, second } = req.payload;
    userId = ObjectId(userId);
    const minusField = from === 'UP' ? 'thumbsUp' : "thumbsDown";
    const addField = minusField == "thumbsUp" ? "thumbsDown" : 'thumbsUp';
    const collection = second ? secondCommentCollection : commentCollection;
    const updateComment = await updateOne({
        collection, _id: commentId, cusData: {
            $pull: { [minusField]: userId },
            $addToSet: { [addField]: userId }
        },
    });
    console.log("评论点赞/踩转换结果:", updateComment);
    if (updateComment.acknowledged) {
        res.json({ message: '成功', code: 0 });
    } else res.status(500).json({ message: '操作失败' });
}

const initialComment = {
    thumbsUp: [],
    thumbsDown: [],
    violation: false,
}

const secondPipeline = (commentId) => [
    { $match: { commentId } },
    {
        $lookup: {
            from: userProfileCollection,
            localField: 'senderId',
            foreignField: '_id',
            as: 'sender'
        }
    },
    {
        $lookup: {
            from: userProfileCollection,
            localField: 'at',
            foreignField: '_id',
            as: 'reply'
        }
    },
    {
        $project: {
            'sender.password': 0,
            'sender.lastUpdate': 0,
            'sender.thumbsUp': 0,
            'sender.thumbsDown': 0,
            'sender.mail': 0,
            'reply.password': 0,
            'reply.lastUpdate': 0,
            'reply.thumbsUp': 0,
            'reply.thumbsDown': 0,
            'reply.mail': 0,
        }
    }, {
        $sort: { _id: -1 }
    }
]

const getCommentByBlog = (aggregate) => async (req, res) => {
    let { _id, limit = 20 } = req.query;
    limit = limit ? Number(limit) : limit;

    const pipeline = [
        { $match: { 'blogId': ObjectId(_id) } },
        {
            $lookup: {
                from: userProfileCollection,
                localField: 'senderId',
                foreignField: '_id',
                as: 'sender'
            }
        },
        {
            $project: {
                'sender.password': 0,
                'sender.lastUpdate': 0,
                'sender.thumbsUp': 0,
                'sender.thumbsDown': 0,
                'sender.mail': 0,
            }
        }, {
            $sort: { _id: -1 }
        }
    ]

    const comments = await aggregate({ collection: commentCollection, pipeline });
    if (!comments) return;
    const { length } = comments;

    for (let index = 0; index < length; index++) {
        const { _id, hasChild } = await comments[index];
        //hasChild 的进行二级评论查询
        if (hasChild) {
            const secondComments = await aggregate({ collection: secondCommentCollection, pipeline: secondPipeline(_id) });
            comments[index].child = secondComments;
        }
    }


    res.json({ message: '查询成功', code: 0, comments });
}

/**
 * @description: 发布评论
 */
const sendComment = (insertOne, updateOne, deleteOne) => async (req, res) => {
    console.log("sendComment:", req.payload);
    const { senderId, blogId, commentId, at, replyUser, ...other } = req.payload;
    const comment = { ...initialComment, ...other, senderId: ObjectId(senderId), blogId: ObjectId(blogId) };
    // 有 commentId & at 视为二级评论
    const collection = commentId ? secondCommentCollection : commentCollection;
    if (commentId) {
        comment.commentId = ObjectId(commentId);//在那条评论下
        comment.at = ObjectId(at);//@谁
    } else {
        comment.hasChild = false;//判断时候该评论下时候有二级评论
    };
    console.log("insert Comment:", comment);
    //插入数据
    const item = await insertOne(collection, comment);
    console.log("插入结果:", item)
    if (!item) return res.end();
    //更改博客评论数
    const updateBlog = await updateOne({
        collection: blogCollection, _id: blogId, cusData: {
            $inc: { commentCount: 1 }
        }
    });
    // 如果是二级评论将一级评论的hasChild改为true
    if (commentId) {
        const updateComment = await updateOne({
            collection: commentCollection,
            _id: commentId,
            data: { hasChild: true }
        });
        console.log("updateComment hasChild:", updateComment);
    }
    console.log("updateBlog:", updateBlog);
    if (item && item.acknowledged && updateBlog) {
        //填充本评论的sender 就是 自己 解析 jwt获得 sender: [{ username, role, _id: at }],
        console.log("sendComment result:", item);
        const returnComment = { ...comment, _id: item.insertedId, sender: [req.userInfo] };
        if (commentId) {
            returnComment.reply = [{ username: replyUser, _id: at }];
        }
        res.json({ message: '发布成功', code: 0, comment: returnComment })
    } else {
        //如果创建评论成功更改博客评论数量失败删除创建的评论 返回错误信息
        (item && item.acknowledged) && deleteOne(collection, item.insertedId);
        res.json({ message: '发布失败', code: 1, comment })
    };
}

module.exports = { violationComment, deleteComment, queryComment, sendComment, getCommentByBlog, thumbsComment, cancelThumbsComment, transformThumbsComment }
/*

db.getCollection('secondComment').aggregate([
    {
        $lookup: {
            from: 'userProfile',
            localField: 'senderId',
            foreignField: '_id',
            as: 'sender'
        }
    }, {
        $match: {
            'blogId': ObjectId("6131ac305ee3cf8a4bf1c63a"),
        }
    }, {
        $lookup: {
            from: 'userProfile',
            localField: 'at',
            foreignField: '_id',
            as: 'AT'
        }
    },
    {
        $project:{
            'sender.password':0,
            'sender.lastUpdate':0,
            'sender.thumbsUp':0,
            'sender.thumbsDown':0,
            'sender.mail':0,
            'AT.password':0,
            'AT.lastUpdate':0,
            'AT.thumbsUp':0,
            'AT.thumbsDown':0,
            'AT.mail':0,
        }
    }
])
*/

/*
aggregate([
    {
        $lookup: {
            from: 'userProfile',
            localField: 'senderId',
            foreignField: '_id',
            as: 'sender'
        }
    }, {
        $match: {
            'blogId': ObjectId("6131ac305ee3cf8a4bf1c63a")
        }
    },
    {
        $project:{
            'sender.password':0,
            'sender.lastUpdate':0,
            'sender.thumbsUp':0,
            'sender.thumbsDown':0,
            'sender.mail':0,
        }
    }
])
*/

// db.getCollection('comment').aggregate([
//     {
//         $match: {
//             'blogId': ObjectId("6131ac305ee3cf8a4bf1c63a")
//         }
//     },
//     {
//         $lookup: {
//             from: 'userProfile',
//             localField: 'senderId',
//             foreignField: '_id',
//             as: 'sender'
//         }
//     },
//     {
//         $project: {
//             'sender.password': 0,
//             'sender.lastUpdate': 0,
//             'sender.thumbsUp': 0,
//             'sender.thumbsDown': 0,
//             'sender.mail': 0,
//         }
//     }
// ])